package com.sun.controller;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.QueryPageParam;
import com.sun.common.Result;
import com.sun.entity.*;
import com.sun.mapper.StorageMapper;
import com.sun.service.*;
import com.sun.until.MyStringUntil;
import com.sun.until.SearchHttpAK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器：记录管理
 * </p>
 *
 * @author rabbiter
 * @since 2023-01-06
 */
@RestController
@RequestMapping("/record")
public class RecordController {
    @Autowired
    private RecordService recordService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private StorageMapper storageMapper;
    @Autowired
    private LogisticsService logisticsService;
    @Autowired
    private GoodstypeService goodstypeService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /*
     *
     * @author rabbiter
     * @date 2023/1/6 20:58
     */
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap<String, Object> param = query.getParam();
        String name = (String) param.get("name");
        String goodstype = (String) param.get("goodstype");
        String cell = (String) param.get("cell");
        String storage = (String) param.get("storage");
        String roleId = (String) param.get("roleId");
        String userId = (String) param.get("userId");

        Page page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        QueryWrapper<Record> queryWrapper = new QueryWrapper();
        queryWrapper.apply("a.goods=b.id and b.storage=c.id and b.goodsType=d.id ");

        if ("2".equals(roleId)) {
             queryWrapper.eq("userId",userId);
        }

        if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
            queryWrapper.like("b.name", name);
        }
        if (StringUtils.isNotBlank(goodstype) && !"null".equals(goodstype)) {
            queryWrapper.eq("d.id", goodstype);
        }
        if (StringUtils.isNotBlank(storage) && !"null".equals(storage)) {
            queryWrapper.eq("c.id", storage);
        }


        IPage result = recordService.pageCC(page, queryWrapper);

        List<Record> records = result.getRecords();

        //权限系统
        String json = (String) redisTemplate.opsForValue().get("user");
        User user = JSONUtil.toBean(json, User.class);

        if ("2".equals(roleId)) {
            //获取名下仓库
            List<String> allCell = storageMapper.getAllCellForAdmin(user.getId(), user.getName());
            Map<String, String> allCellMap = new HashMap<>();
            //
            for (String s : allCell) {
                allCellMap.put(s, s);
            }
            Iterator<Record> iterator = records.iterator();
            while (iterator.hasNext()) {
                Record record = iterator.next();
                if (!allCellMap.containsKey(record.getCell())) {
                    iterator.remove();
                }


            }
        }

        return Result.success(result.getRecords(), result.getTotal());
    }

    /*
     * 新增记录
     * @author rabbiter
     * @date 2023/1/6 21:21
     */
    @PostMapping("/save")
    public Result save(@RequestBody Record record) {

        //权限系统
        String json = (String) redisTemplate.opsForValue().get("user");
        User user = JSONUtil.toBean(json, User.class);

        Goods goods = goodsService.getById(record.getGoods());
        int n = record.getCount();
        // 出库
        if ("2".equals(record.getAction())) {
            n = -n;
            record.setCount(n);
        }
        int num = goods.getCount() + n;
        if (num < 0) {
            return Result.fail();
        }
        goods.setCount(num);
        goodsService.updateById(goods);
        record.setCreatetime(LocalDateTime.now());
        record.setCell(goods.getCell());
        record.setUserid(user.getId());
        return recordService.save(record) ? Result.success() : Result.fail();
    }


    @PostMapping("/saveToOther")
    public Result saveToOther(@RequestBody Logistics logistics) throws Exception {
        //货物名称
        String name = logistics.getName();
        if (name == null) {
            return Result.fail(500, "请输入物品名");
        }

        //货物数量
        Integer count = logistics.getCount();
        if (count == null) {
            return Result.fail(500, "数量为空");
        }

        //发货仓库
        String output = logistics.getOutput();

        //收货仓库
        String input = logistics.getInput();
        if (input == null) {
            return Result.fail(500, "请输入收货仓库");
        }
        QueryWrapper<Storage> storageWrapper1 = new QueryWrapper<>();
        storageWrapper1.eq("cell", output);
        List<Storage> list1 = storageService.list(storageWrapper1);
        Storage outputStorage = list1.get(0);


        QueryWrapper<Storage> storageWrapper2 = new QueryWrapper<>();
        storageWrapper2.eq("cell", input);
        List<Storage> list2 = storageService.list(storageWrapper2);
        Storage inputStorage = list2.get(0);


        //@ApiModelProperty(value = "仓库类型")
        logistics.setStorageType(outputStorage.getName());

        //@ApiModelProperty(value = "物品分类")
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("name", logistics.getName());
        List<Goods> list = goodsService.list(goodsQueryWrapper);
        String goodstype = list.get(0).getGoodstype();
        Goodstype byId = goodstypeService.getById(goodstype);
        logistics.setGoodType(byId.getName());

        //@ApiModelProperty(value = "发货仓库经纬度")
        logistics.setOutpoint(outputStorage.getAddrpoint());

        //@ApiModelProperty(value = "收货仓库经纬度")
        logistics.setInpoint(inputStorage.getAddrpoint());

//        @ApiModelProperty(value = "发货人")
        String admin = outputStorage.getAdmin();


        User byId1 = userService.getById(admin);
        if (byId1 == null) {
            logistics.setSender(admin);
        } else {
            logistics.setSender(byId1.getName());
        }

//        @ApiModelProperty(value = "收货人")
        String admin2 = inputStorage.getAdmin();
        User byId2 = userService.getById(admin2);
        if (byId2 == null) {
            logistics.setReceiver(admin2);
        } else {
            logistics.setReceiver(byId2.getName());
        }

//        @ApiModelProperty(value = "发货地址")
        logistics.setDeliveryAddress(outputStorage.getAddress());

//        @ApiModelProperty(value = "收货地址")
        logistics.setShippingAddress(inputStorage.getAddress());


//        @ApiModelProperty(value = "发货时间")
        logistics.setDeliveryTime(new Date());

        String outpoint = outputStorage.getAddrpoint();
        Map<String, Object> outpointMap = JSONUtil.toBean(outpoint, Map.class);
        String inpoint = inputStorage.getAddrpoint();
        Map<String, Object> inpointMap = JSONUtil.toBean(inpoint, Map.class);


        Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("origin", MyStringUntil.get6Num(outpointMap.get("lat")) + "," + MyStringUntil.get6Num(outpointMap.get("lng")));
        objectObjectHashMap.put("destination", MyStringUntil.get6Num(inpointMap.get("lat")) + "," + MyStringUntil.get6Num(inpointMap.get("lng")));
        Map<String, Object> map = SearchHttpAK.main(objectObjectHashMap);


        //预计配送时间
        JSONObject jsonObject = new JSONObject(map.get("result"));
        JSONArray routes = (JSONArray) jsonObject.get("routes");
        JSONObject routes0 = (JSONObject) routes.get(0);
        Integer duration = (Integer) routes0.get("duration");
        logistics.setEstimatedDeliveryTime(String.valueOf(NumberUtil.div((Number) duration, (Number) 3600, 2)));


        logistics.setLogisticsStatus("待审批");

        logisticsService.save(logistics);

        return Result.success();
    }


}
